package top.codedance.iotp.client.plugins.sync.com.listenner;

import top.codedance.iotp.client.plugins.sync.com.ComClient;
import top.codedance.iotp.common.util.BytesBuilder;
import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;

public class SerialPortListener implements SerialPortDataListener {

    private ComClient cc;
    private BytesBuilder gbb = new BytesBuilder();

    public SerialPortListener(ComClient cc){
        this.cc = cc;
    }

    @Override
    public int getListeningEvents() {
        return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
    }

    public synchronized void serialEvent(SerialPortEvent serialPortEvent) {
        if (serialPortEvent.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE)
            return;
        BytesBuilder bb = new BytesBuilder();
        SerialPort serialPort = serialPortEvent.getSerialPort();
        int avai = serialPort.bytesAvailable();
        while (avai > 0) {
            byte[] data = new byte[avai];
            serialPort.readBytes(data, avai);
            bb.append(data);
            avai = serialPort.bytesAvailable();
        }
        byte[] bytes = bb.toArray();
        gbb.append(bytes);
        byte[] result = gbb.toArray();
        cc.appendResult(result);
        gbb = new BytesBuilder();
    }
}
